package risk.control.project.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import risk.control.project.entity.repository.UserBean;
import risk.control.project.framework.PostController;
import risk.control.project.service.AccountLockService;
import risk.control.project.service.CaptchaService;
import risk.control.project.service.UserService;

import java.util.HashMap;


@RestController
@RequestMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
public class MAIN_000_000_001 extends PostController {
    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_000_001.class);

    private final UserService userService;
    private final CaptchaService captchaService;
    private final AccountLockService accountLockService;

    public MAIN_000_000_001(UserService userService, CaptchaService captchaService, AccountLockService accountLockService) {
        this.userService = userService;
        this.captchaService = captchaService;
        this.accountLockService = accountLockService;
    }

    //登录接口-账号密码登录
    @PostMapping(value = "/000_000_001")
    public String doPost(HttpServletRequest request) {
        return handleRequest(request);
    }

    @Override
    protected String postRequest(HashMap<String, String> param) {
        String requestBody = param.get("requestBody");
        JSONObject jsonObject = (JSONObject) JSON.parse(requestBody);
        String captchaKey = jsonObject.getString("captchaKey");
        String captcha = jsonObject.getString("captcha");
        String name = jsonObject.getString("userName");
        String userPwd = jsonObject.getString("pwd");
        String channel = jsonObject.getString("channel");
        //非空判断
        if (captcha == null || captcha.isEmpty()) {
            return generateFail("验证码为空");
        }
        if (name == null || name.isEmpty() || userPwd == null || userPwd.isEmpty()) {
            return generateFail("用户名或密码为空");
        }
        //验证码判断
        HashMap<String, String> captchaVerify = captchaService.verify(captcha, captchaKey);
        if (!captchaVerify.get("state").equals("000")) {
            return generateFail(captchaVerify.get("msg"));
        }
        //用户存在判断->查库
        UserBean userBean = userService.getUserForName(name);
        if (userBean == null) {
            return generateFail("当前用户不存在");
        }
        //登录失败次数判断
        int errorCount = accountLockService.getErrorCount(name);
        int macCount = 3;
        if (errorCount >= macCount) {
            //锁定账号
            return generateFail("当前账号已连续输错" + macCount + "次，请5分钟后再尝试");
        }
        //验证密码
        String pwd = userBean.userPwd;
        String userName = userBean.userName;
        String userId = userBean.userId;
        if (!pwd.equals(userPwd)) {
            //记录错误次数
            accountLockService.setErrorCount(userName);
            return generateFail("密码输入错误");
        }
        //根据渠道标识区分
        if (channel == null || channel.isEmpty()) {
            return generateFail("渠道标识为空");
        }
        String permissionLevel = userBean.userPermissionLevel;
        if (channel.equals("android")) {
            //完成->颁发token
            accountLockService.clearLoginLock(userName);//清除记录次数
            String token = generateToken(userId);
            //封装响应体
            HashMap<String, String> resMap = new HashMap<>();
            resMap.put("token", token);
            return generateSucceed(resMap);
        } else if (channel.equals("web")) {
            //web端，只有权限为0或者1，超级管理员或者网点管理员才能登录web端
            if (permissionLevel.equals("0") || permissionLevel.equals("1")) {
                //完成->颁发token
                accountLockService.clearLoginLock(userName);//清除记录次数
                String token = generateToken(userId);
                //封装响应体
                HashMap<String, String> resMap = new HashMap<>();
                resMap.put("token", token);
                return generateSucceed(resMap);
            } else {
                return generateFail("对不起，您没有权限！");
            }
        } else {
            return generateFail("错误的渠道标识");
        }
    }
}
